import { useEffect, useRef, useState } from 'react';
import sharedWebSocket from '@/services/sharedWebSocket';

export const useWebSocket = () => {
  const [isConnected, setIsConnected] = useState(false);
  const isConnectedRef = useRef(false);

  const connect = (id,token) => {
    if (id && token && !isConnectedRef.current) {
      sharedWebSocket.connect(id,token);
      isConnectedRef.current = true;
      setIsConnected(true);
    }
  };

  const disconnect = () => {
    
    if (isConnectedRef.current) {
      sharedWebSocket.disconnect();
      isConnectedRef.current = false;
      setIsConnected(false);
    }
  };

  useEffect(() => {
    return () => {
      disconnect();
    };
  }, []);

  return {
    isConnected,
    connect,
    disconnect
  };
};